package com.hoyue.system.service.impl;

import com.hoyue.common.utils.ShiroUtils;
import com.hoyue.system.bean.User;
import com.hoyue.system.dao.UserMapper;
import com.hoyue.system.service.UserService;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 空白
 * @version 1.0
 * Create by 2019/08/08 01:48
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public User getUserByEmail(String email) {
        return userMapper.getUserByEmail(email);
    }

    @Override
    public int insertUser(User user) {
        /*获取用户输入信息*/
        String email = user.getEmail();
        String password = user.getPassword();
        /*设置加密规则*/
       // 获取一个随机盐值
        String salt = new SecureRandomNumberGenerator().nextBytes().toString();
       // 设置加密次数
        int times = 2;
       // 使用MD5进行散列加密
        String algorithmName = "md5";
       // 将用户输入的密码进行加密,并储存在encodedPassword中
        String encodedPassword = new SimpleHash(algorithmName, password, salt + email, times).toString();
       // 将加密结果放入用户信息中
        user.setPassword(encodedPassword);
        user.setSalt(salt);
        // userMapper.insertUser(user);
       // 执行写入用户信息方法
        userMapper.insertUser(user);
        // 返回写入用户信息的id,因为id的自增的，所以我们需要插入后才知道id
        return user.getId();
    }

    @Override
    public User getLoginUser() {
        // 获取用户email
        String email = ShiroUtils.getUserEmail();
        if(email == null) {
            return null;
        }
        return userMapper.getUserByEmail(email);
    }

    @Override
    public List<String> selectGradeList() {
        return userMapper.selectGradeList();
    }
}
